﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using Universum.Infrastructure.Persistence;
using Universum.Infrastructure.Persistence.Queries.Blog;
using TBlog = Universum.Model.Domain.Blogs.Blog;
namespace Universum.Model.Services.Blog
{
	public class BlogServiceImpl : IBlogService
	{
		IRepository _Repository;
		public BlogServiceImpl(IRepository repository)
		{
			this._Repository = repository;
		
		}
		#region IBlogService Members

		public Universum.Model.Domain.Blogs.Blog GetBlogByOwner(string owner)
		{
			return _Repository.Query(new BlogByOwner(owner)).FirstOrDefault();
		}

		public TBlog CreateBlog(string owner)
		{
			var blog = new TBlog { Created= DateTime.Now, ID = Guid.NewGuid(), Owner = owner };
			_Repository.SaveOrUpdate(blog);
			return blog;
		}

		public void SaveOrUpdate(TBlog blog)
		{
			_Repository.SaveOrUpdate(blog);
		}
				
		public void RemoveBlog(Universum.Model.Domain.Blogs.Blog blog)
		{
			_Repository.Remove(blog);
		}


		public int GetBlogArticlesCountFor(Guid guid)
		{
			var result = _Repository.Query(new PublishedBlogArticleByBlogId(guid)).Count();
			return result;
		}

		public IList<Universum.Model.Domain.Blogs.BlogArticle> GetBlogArticlesPage(Guid guid, int fromIndex, int articlesPerPage)
		{
			int articlesToSkipCount = fromIndex*articlesPerPage;

			var result = _Repository.Query(new BlogArticleByBlogId(guid)).OrderByDescending(item => item.Publish).Skip(articlesToSkipCount).Take(articlesPerPage).ToList();
			return result;
		}
		#endregion

		#region IBlogService Members


		public List<Universum.Model.Domain.Blogs.Blog> GetLatestBlogs(int numberOfBlogs)
		{
			return _Repository.Query<Domain.Blogs.Blog>().OrderBy(it => it.Created).Take(numberOfBlogs).ToList();
		}

		public List<Universum.Model.Domain.Blogs.BlogArticle> GetLatestArticles(int numberOfArticles)
		{
			return _Repository.Query<Universum.Model.Domain.Blogs.BlogArticle>().OrderByDescending(it => it.Publish).Take(numberOfArticles).ToList();
		}

		#endregion

		#region IBlogService Members


		public IList<Universum.Model.Domain.Blogs.BlogArticle> GetPublishedBlogArticlesPage(Guid guid, int fromIndex, int articlesPerPage)
		{
			int articlesToSkipCount = fromIndex * articlesPerPage;

			var result = _Repository.Query(new PublishedBlogArticleByBlogId(guid)).OrderByDescending(item => item.Publish).Skip(articlesToSkipCount).Take(articlesPerPage).ToList();
			return result;
		}

		#endregion

		#region IBlogService Members


		public List<string> GetUsersWithBlogs()
		{
			return (from b in _Repository.Query<Universum.Model.Domain.Blogs.Blog>()
					select b.Owner).ToList();
		}

		#endregion
	}
}
